from wtforms import Form, StringField, IntegerField, FloatField
from wtforms.validators import DataRequired, Length, NumberRange, ValidationError


class NewProductForm(Form):
    img = StringField(validators=[DataRequired(message='必须上传零食图片')])
    name = StringField(validators=[DataRequired('必须填写零食的名字'), Length(3, 40)])
    reserve = IntegerField(validators=[DataRequired('必须填写整数库存'), NumberRange(0, 999999)])
    price = FloatField(validators=[DataRequired('必须填写数字单价')])

    def validate_img(self, field):
        s = field.data
        if not ('.' in s and s.rsplit('.', 1)[1] in {'png', 'jpg', 'jpeg', 'gif', 'webp'}):
            raise ValidationError('请不要上传非法文件名')
